import { basket, prodCount, prodtotal, changeItem, deleteItem } from "@/services";

const state = {
  basketData: {},
  prodCount: 0,
  allChecked: false,
  totalMoney: 0,
};

const getters = {};

const mutations = {
  update(state, payload) {
    for (let key in payload) {
      state[key] = payload[key];
    }
  },
  settatalPayData(state, payload) {
    // 全选
    state.allChecked = payload;
    state.basketData.forEach((item) => {
      item.checked = payload;
    });
  },
};

const actions = {
  async basketList({ commit }, payload) {
    let result = await basket();
    
    if (result) {
      result[0].shopCartItemDiscounts[0].shopCartItems.forEach((item) => {
        let MyKey = "checked";
        item[MyKey] = false;
      });

      commit("update", {
        basketData: result[0].shopCartItemDiscounts[0].shopCartItems,
      });
    }
  },
  async basketProdCount({ commit }, payload) {
    let result = await prodCount();
    if (result) {
      commit("update", { prodCount: result });
    }
  },
  async basketProdtotal({ commit }, payload) {
    let result = await prodtotal(payload);
    if (result) {
      commit("update", { totalMoney: result.totalMoney });
    }
  },
  async basketchange({ commit }, payload) {
    let result = await changeItem(payload);
    if (result) {
      commit("update");
    }
  },
  // 删除
  async delchange({ dispatch,commit }, payload) {
    await deleteItem(payload);
    await dispatch('basketList');
    
  },
};

export default {
  namespaced: true,
  modules: {},
  state,
  getters,
  mutations,
  actions,
};
